﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Collections.ObjectModel;
using System.Threading;
namespace SerialIO
{
    enum Commands  {
        GET_TEMP1 = (1 << 7) | (1 << 0),
        GET_TEMP2 = (1 << 7) | (1 << 1),
        GET_TEMP3 = (1 << 7) | (1 << 2)

    }
    class SerialCom
    {
        private bool IsRunning;
        public SerialPort _port { get; private set; }
        public SerialCom()
        {
        }

        internal void SetPort(String port, SerialDataReceivedEventHandler callBack)
        {

            _port = new SerialPort(port, 9600, Parity.None, 8, StopBits.Two);
            _port.Encoding = Encoding.UTF8;
            IsRunning = true;
            _port.Open();
            _port.DataReceived += callBack;
            new Thread(Read);
        }

        internal Collection<String> GetPorts()
        {
            return new Collection<String>(SerialPort.GetPortNames());
        }

        public void send(Commands command)
        {
            _port.Write(new byte[]{(byte)command}, 0, 1);
        }

        public void stop(){
            IsRunning = false;
        }
        public void Read()
        {
            while (IsRunning)
            {
                while (_port.IsOpen)
                {
                    while (_port.BytesToRead != 0)
                    {
                        LogConsole.WriteLine(String.Format("Received: {0}", _port.ReadChar()));
                    }
                }
            }
        }
    }
}
